﻿
function formatTime(time,showSec)
    local hours = floor(mod(time, 86400)/3600)
    local minutes = floor(mod(time,3600)/60)
    local seconds = floor(mod(time,60))

    if showSec then 
        return format("%d时%d分%d秒", hours, minutes, seconds)
    else
        return format("%s:%s",hours,minutes)
    end
end

function refreshSoulTowerTime()
    local topCenter = C_UIWidgetManager.GetTopCenterWidgetSetID()
    local widgets = C_UIWidgetManager.GetAllWidgetsBySetID(topCenter)

    for _, w in pairs(widgets) do
        --print(w.widgetID)
        if w.widgetID == 3119 then
            --print(C_UIWidgetManager.GetIconAndTextWidgetVisualizationInfo(3119).text)
            local text = C_UIWidgetManager.GetIconAndTextWidgetVisualizationInfo(3119).text
            local timeStr = select(3,strsplit(" ", text))
            local _hour,_min  = strsplit(":",timeStr)
            
            local curH = tonumber(date("%H",time()))
            local curM = tonumber(date("%M",time()))
            
            local durationTime =  (_hour) * 3600 + (_min) * 60
            --local countDown = correct(GetTime())
            local endTime =  (curH+_hour) * 3600 + (curM+_min) * 60
            local delayTimes = delayTime(tonumber(_hour), tonumber(_min))
            
            -- 保存变量
            -- TerokkarSv['towerTime']  = GetServerTime() + durationTime + delayTimes
            TerokkarSv['towerTime']  = GetServerTime() + durationTime
            TerokkarSv['endTime']  = endTime + delayTimes

            -- print('倒计时:',TerokkarSv['towerTime'])
            -- print('结束时间:',TerokkarSv['endTime'])

        end
    end
    
end

function delayTime(hour,min)
    local delaySeconds = (hour > 0 and hour * 60 or 0 + min > 0  and min or 0) * 3
    return delaySeconds
end



-- 判断发送消息
function sendMsg(min, Tips)

    local msgStr = ""
    local cooldownTime = TerokkarSv['towerTime']

    -- 判断是否已经等于
    if cooldownTime-time() == 60 * min then
        -- print('TT 123: ', TerokkarSv["__notice__"][min])

        if TerokkarSv["__notice__"][min] == nil then
            PlaySound(8960)

            msgStr = string.format(
                "友情提示：泰罗卡森林占塔<日常> 剩余  %d分钟 ",
                min
            )

            for ChannelName,SendType in pairs(Tips) do
                if SendType then
                    SendChatMessage(msgStr, ChannelName)
                end
            end

            TerokkarSv["__notice__"][min] = false

        end

    end

end

-- 注册
local _Frame = CreateFrame("Frame", nil, UIParent);
local _Title = _Frame:CreateFontString(nil, "OVERLAY");
-- 显示时间
local _timeW = _Frame:CreateFontString(nil, "OVERLAY")
-- _Frame:RegisterEvent("UPDATE_UI_WIDGET");
-- _Frame:RegisterEvent("TRADE_SKILL_SHOW");
-- _Frame:RegisterEvent("TRADE_SKILL_CLOSE");
-- _Frame:RegisterEvent("PLAYER_ENTERING_WORLD");

_Frame:RegisterEvent("AREA_POIS_UPDATED");
_Frame:RegisterEvent("ZONE_CHANGED_NEW_AREA");
_Frame:RegisterEvent("ZONE_CHANGED_INDOORS");
_Frame:RegisterEvent("ADDON_LOADED")
_Frame:SetScript("OnEvent", function (self, event, ...)
	if event == "ADDON_LOADED" then
        TerokkarSv = TerokkarSv or {true, true}
		self:UnregisterEvent("ADDON_LOADED")
        -- 初始化布局
        initLayout()
    end
    _Init(event, ...)
end);

-- 拖动
_Frame:SetScript("OnMouseDown", function(self, button)
    if button == "LeftButton" then
        self:StartMoving();
    else
        --ALADROP(board, "BOTTOMLEFT", drop_menu_table);
    end
end);
_Frame:SetScript("OnMouseUp", function(self, button)
    self:StopMovingOrSizing();
    TerokkarSv.pos = { self:GetPoint(), };
    for i, v in ipairs(TerokkarSv.pos) do
        if type(v) == 'table' then
            TerokkarSv.pos[i] = v:GetName();
        end
    end
end);


-- 初始化
function _Init(event, ...)

    -- 判断是否在泰罗卡
    if C_Map.GetBestMapForUnit("player") ==1952 then
        -- print('已经进入泰罗卡')
        refreshSoulTowerTime()
    else
        -- print('没有进入泰罗卡')
    end


    --更新ui
    updateUi()

    -- 恢复上次位置
    if TerokkarSv.pos then
        _Frame:ClearAllPoints();
        _Frame:SetPoint(TerokkarSv.pos[1], TerokkarSv.pos[2], TerokkarSv.pos[3], TerokkarSv.pos[4], TerokkarSv.pos[5]);
    end

    -- SendChatMessage("msgStr", "WHISPER", nil, UnitName("player") )

    -- 通知列表
    TerokkarSv["__notice__"] = {}

    -- 定时
    C_Timer.NewTicker(1.0, updateUi)

end

-- 设置布局
function initLayout()
    _Frame:SetSize(160, 80)
    -- 设置背景
    _Frame:SetPoint("TOP",0, -150);
    _Frame:SetMovable(true);
    _Frame.Bg = _Frame:CreateTexture(nil, "BACKGROUND")
    _Frame.Bg:SetTexture("Interface\\LevelUp\\MinorTalents")
    _Frame.Bg:SetPoint("TOP")
    _Frame.Bg:SetSize(160, 80)
    _Frame.Bg:SetTexCoord(0, 400/520, 341/512, 407/512)
    _Frame.Bg:SetVertexColor(1, 1, 1, 0.5)
    -- 设置标题
    _Title:SetFont(GameFontNormal:GetFont(), 14)
    _Title:SetPoint("CENTER", _Frame, "TOP", 0, -15 )
    _Title:SetText("\124cffff8000泰罗卡站塔\124r ")

    -- 倒计时
    _timeW:SetFont(GameFontNormal:GetFont(), 14)
    _timeW:SetPoint("CENTER", _Frame, "BOTTOM", 0, 27)
end


local msgStr = ''
local Tips = {}
local minNotice = {}

-- 提示时间列表
minNotice[1] = false
minNotice[5] = true
minNotice[10] = true
minNotice[15] = true
minNotice[20] = false
minNotice[30] = false
minNotice[59] = false

-- 公会
Tips['GUILD'] = true
Tips['PARTY'] = false
Tips['RAID'] = false
Tips['YELL'] = false
Tips['SAY'] = false
-- 私密自己
-- Tips['whisper'] = true


-- 更新界面 UI
function updateUi()
    local cooldownTime = TerokkarSv['towerTime']
    local timeStr = '\124cffff0000占塔时间已过期 \n请重新进入 <泰罗卡森林>\124r'

    -- 判断是否过期
    if isOverdue(cooldownTime) then

        -- TerokkarSv['towerTime'] = cooldownTime -1000

        -- 更新显示
        text = formatTime(TerokkarSv['endTime'])
        timeStr = formatTime(cooldownTime-time(), true)
        text = "\124cff00ff00".. timeStr .. "\124r\n\n"..text

        -- 判斷是否开启
        for key,value in pairs(minNotice) do

            -- 判断是否开启扩展提示
            if value then
                -- 執行发现
                sendMsg(key, Tips)
            end
        end

        _timeW:SetText(text)

    else
        _timeW:SetText(timeStr)
    end
    

end

-- 判断是否过期
function isOverdue(cooldownTime)
    if cooldownTime-time() > 0  then
        return true
    else
        return false
    end
end
